import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeepPartial, FindOptionsWhere, Repository } from 'typeorm';
import { TimetableRecord } from './models/timetableRecord.entity';
import { TimetableRecordType } from './dto/timetableRecord.type';

@Injectable()
export class TimetableRecordService {
  constructor(
    @InjectRepository(TimetableRecord)
    private readonly TimetableRecordRepository: Repository<TimetableRecord>,
  ) {}

  async create(entity: DeepPartial<TimetableRecord>): Promise<TimetableRecord> {
    return await this.TimetableRecordRepository.save(
      this.TimetableRecordRepository.create(entity),
    );
  }

  async findById(id: string): Promise<TimetableRecord> {
    return this.TimetableRecordRepository.findOne({
      where: {
        id,
      },
    });
  }

  async updateById(
    id: string,
    entity: DeepPartial<TimetableRecord>,
  ): Promise<boolean> {
    const existEntity = await this.findById(id);
    if (!existEntity) {
      return false;
    }
    Object.assign(existEntity, entity);
    const res = await this.TimetableRecordRepository.save(existEntity);
    return !!res;
  }

  async findTimetableRecords(arg: {
    where: FindOptionsWhere<TimetableRecordType>;
    start: number;
    length: number;
  }): Promise<[TimetableRecordType[], number]> {
    const { where, start, length } = arg;
    console.log(start, length);
    return this.TimetableRecordRepository.findAndCount({
      take: length,
      skip: start,
      where,
      order: {
        createdAt: 'ASC',
      },
    });
  }

  async deleteById(id: string, userId: string): Promise<boolean> {
    const res1 = await this.TimetableRecordRepository.update(id, {
      deletedBy: userId,
    });
    if (res1) {
      const res = await this.TimetableRecordRepository.softDelete(id);
      if (res.affected > 0) {
        return true;
      }
    }
    return false;
  }
}
